"use strict";
// 1.1 生成指定范围随机数
function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 示例
console.log(getRandomNumber(5, 10)); // 输出5-10之间的随机整数
// 2.1 数组乱序
function shuffleArray(array) {
    return array.sort(() => Math.random() - 0.5);
}
// 2.2 数组扁平化
function flattenArray(arr) {
    return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}
// 2.3 数组中获取随机数
function getRandomElement(array) {
    return array[Math.floor(Math.random() * array.length)];
}
console.log(getRandomElement([1, 2, 3, 4, 5])); // 随机返回数组中的一个元素
// 3.1 生成随机字符串
function generateRandomString(length = 8) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}
console.log(generateRandomString(10));
// 3.2 字符串首字母大写
function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}
// 3.3 手机号中间四位变成*
function maskPhoneNumber(phone) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}
// 3.4 驼峰命名转换成短横线命名  userName UserName user_name
function camelToKebab(str) {
    return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
// 示例
console.log(camelToKebab('userName')); // "user-name"
console.log(camelToKebab('UserName')); // "user-name"
// 3.5 短横线命名转换成驼峰命名
function kebabToCamel(str) {
    return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}
// 示例
console.log(kebabToCamel('user-name')); // "userName"
// 4.1 数字转化为大写金额
function numberToChinese(num) {
    if (isNaN(num))
        return '非法数字';
    const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '兆'];
    const decimals = ['角', '分', '厘'];
    let str = '';
    num = Math.abs(num);
    // 整数部分
    const integer = Math.floor(num);
    if (integer > 0) {
        let integerStr = '';
        const integerArr = integer.toString().split('').reverse();
        integerArr.forEach((item, index) => {
            const digit = digits[parseInt(item)];
            const unit = units[index];
            integerStr = digit + unit + integerStr;
        });
        str += integerStr + '元';
    }
    // 小数部分
    const decimal = Math.round((num - integer) * 100) / 100;
    if (decimal > 0) {
        const decimalStr = decimal.toString().substring(2);
        for (let i = 0; i < decimalStr.length; i++) {
            if (i >= decimals.length)
                break;
            str += digits[parseInt(decimalStr[i])] + decimals[i];
        }
    }
    else {
        str += '整';
    }
    return str;
}
// 示例
console.log(numberToChinese(12345.67)); // "壹万贰仟叁佰肆拾伍元陆角柒分"
// 5.1 存储 localStorage
function setLocalStorage(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
}
// 5.2 获取 localStorage
function getLocalStorage(key) {
    const value = localStorage.getItem(key);
    return value ? JSON.parse(value) : null;
}
// 5.3 删除 localStorage
function removeLocalStorage(key) {
    localStorage.removeItem(key);
}
// 6.1 设置 cookie
function setCookie(name, value, days = 7) {
    const date = new Date();
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${encodeURIComponent(value)};expires=${date.toUTCString()};path=/`;
}
// 6.2 读取 cookie
function getCookie(name) {
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
        const [key, value] = cookie.trim().split('=');
        if (key === name)
            return decodeURIComponent(value);
    }
    return null;
}
// 7.1 正则校验身份证号码
function validateIDCard(id) {
    const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
    return reg.test(id);
}
// 7.2 正则校验是否包含中文
function hasChinese(str) {
    return /[\u4e00-\u9fa5]/.test(str);
}
// 8.1 获取URL参数列表
// 8.1 获取URL参数列表
function getUrlParams() {
    const params = {};
    new URLSearchParams(window.location.search).forEach((value, key) => {
        params[key] = value;
    });
    return params;
}
function buildUrlParams(params) {
    const searchParams = new URLSearchParams();
    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const value = params[key];
            if (value !== undefined && value !== null) {
                searchParams.append(key, String(value));
            }
        }
    }
    return searchParams.toString();
}
// 使用示例
const params = {
    name: "John Doe",
    age: 30,
    active: true,
    query: "typescript url params"
};
const queryString = buildUrlParams(params);
console.log(queryString);
// 输出: "name=John+Doe&age=30&active=true&query=typescript+url+params"
// 9.1 判断是移动还是PC设备
function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
// 9.4 判断是Windows还是Mac系统
function getOS() {
    const userAgent = navigator.userAgent;
    if (/Mac/i.test(userAgent))
        return 'Mac';
    if (/Win/i.test(userAgent))
        return 'Windows';
    return 'Unknown';
}
// 10.1 滚动到页面顶部
function scrollToTop() {
    window.scrollTo({
        top: 0,
        behavior: 'smooth' // 平滑滚动
    });
    // 或者使用兼容性更好的写法
    // const top = document.documentElement.scrollTop || document.body.scrollTop;
    // if (top > 0) {
    //   window.requestAnimationFrame(scrollToTop);
    //   window.scrollTo(0, top - top / 8);
    // }
}
// 10.4 获取可视窗口高度
function getViewportHeight() {
    return window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
}
// 11.2 格式化时间
function formatTime(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
    if (!(date instanceof Date)) {
        date = new Date(date);
    }
    const padZero = (num) => (num < 10 ? `0${num}` : num.toString());
    const map = {
        'YYYY': date.getFullYear().toString(),
        'MM': padZero(date.getMonth() + 1),
        'DD': padZero(date.getDate()),
        'HH': padZero(date.getHours()),
        'mm': padZero(date.getMinutes()),
        'ss': padZero(date.getSeconds())
    };
    return fmt.replace(/(YYYY|MM|DD|HH|mm|ss)/g, (match) => map[match]);
}
// 12.2 防抖函数
function debounce(fn, delay = 300) {
    let timer = null;
    return function (...args) {
        if (timer)
            clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
            timer = null;
        }, delay);
    };
}
// 12.3 节流函数
function throttle(fn, interval = 300) {
    let lastTime = 0;
    return function (...args) {
        const now = Date.now();
        if (now - lastTime >= interval) {
            fn.apply(this, args);
            lastTime = now;
        }
    };
}
// 12.5 对象深拷贝
function deepClone(obj, hash = new WeakMap()) {
    // 处理基本类型和 null/undefined
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    // 处理日期对象
    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }
    // 处理正则表达式
    if (obj instanceof RegExp) {
        return new RegExp(obj.source, obj.flags);
    }
    // 处理数组
    if (Array.isArray(obj)) {
        return obj.map(item => deepClone(item, hash));
    }
    // 处理 Map
    if (obj instanceof Map) {
        const clonedMap = new Map();
        obj.forEach((value, key) => {
            clonedMap.set(deepClone(key, hash), deepClone(value, hash));
        });
        return clonedMap;
    }
    // 处理 Set
    if (obj instanceof Set) {
        const clonedSet = new Set();
        obj.forEach(value => {
            clonedSet.add(deepClone(value, hash));
        });
        return clonedSet;
    }
    // 检查循环引用
    if (hash.has(obj)) {
        return hash.get(obj);
    }
    // 处理普通对象
    const clonedObj = Object.create(Object.getPrototypeOf(obj));
    hash.set(obj, clonedObj);
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            clonedObj[key] = deepClone(obj[key], hash);
        }
    }
    return clonedObj;
}
// 使用示例
const complexObj = {
    date: new Date(),
    regex: /test/g,
    map: new Map([['key', 'value']]),
    set: new Set([1, 2, 3]),
    selfRef: {}
};
complexObj.selfRef = complexObj;
const clonedComplex = deepClone(complexObj);
console.log(clonedComplex);
